package dao.fake;

import interfaceDAO.IDAOUser;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import domain.User;

public class FakeDAOUser implements IDAOUser {
	private static List<User> users = new ArrayList<User>();

	public static File getDataFile() {
		File dataFile = new File(System.getProperty("java.io.tmpdir"), "bike_app_users.dat");
		return dataFile;
	}

	@SuppressWarnings("unchecked")
	public static void loadUsers() {
		if (users.isEmpty()) {
			try {
				File dataFile = getDataFile();
				InputStream is = new FileInputStream(dataFile);
				users = (List<User>) new ObjectInputStream(is).readObject();
				is.close();
			} catch (Exception e) {
				users = new ArrayList<User>();
				e.printStackTrace();
			}
		}
	}

	public static void saveUsers() {
		try {
			File dataFile = getDataFile();
			OutputStream os = new FileOutputStream(dataFile);
			new ObjectOutputStream(os).writeObject(users);
			os.close();
		} catch (Exception e) {
			users = new ArrayList<User>();
			e.printStackTrace();
		}
	}

	@Override
	public User addUser(String firstName, String lastName, String email,
			String pseudo, String password) {
		loadUsers();
		for (User user : users) {
			if (user.getPseudo().equals(pseudo)) {
				throw new IllegalArgumentException("Pseudo already exists :"
						+ pseudo);
			} else if (user.getEmail().equals(email)) {
				throw new IllegalArgumentException("Email already exists :"
						+ email);
			}
		}

		User newUser = new User();

		newUser.setFirstName(firstName);
		newUser.setLastName(lastName);
		newUser.setPseudo(pseudo);
		newUser.setPassword(password);
		newUser.setEmail(email);

		users.add(newUser);
		saveUsers();

		return newUser;

	}

	@Override
	public Boolean isUser(String pseudo, String password) {
		loadUsers();
		for (User user : users) {
			if (user.getPseudo().equals(pseudo)
					&& user.getPassword().equals(password)) {
				return true;
			}
		}
		return false;
	}

	@Override
	public Boolean deleteUser(String pseudo) {
		User user = getUser(pseudo);
		if (user != null) {
			users.remove(user);
			saveUsers();
			return true;
		}
		return false;
	}

	@Override
	public User getUser(String pseudo) {
		loadUsers();
		for (User user : users) {
			if (user.getPseudo().equals(pseudo)) {
				return user;
			}
		}
		return null;
	}

}
